// controllers/payment.controller.js
const PaymentService = require('../services/payment.service');
const logger = require('../logger');

/**
 * 创建支付订单
 */
async function createPaymentOrder(req, res) {
  try {
    const { productType, productId, paymentMethod } = req.body;
    const userId = req.user.userId;
    
    const result = await PaymentService.createPaymentOrder({
      userId,
      productType,
      productId,
      paymentMethod
    });
    
    res.json(result);
  } catch (error) {
    logger.error('创建支付订单失败', { error: error.message });
    res.status(500).json({ error: '创建支付订单失败' });
  }
}

/**
 * 支付回调处理
 */
async function paymentCallback(req, res) {
  try {
    const callbackData = req.body;
    
    await PaymentService.processPaymentCallback(callbackData);
    
    res.json({ success: true });
  } catch (error) {
    logger.error('处理支付回调失败', { error: error.message });
    res.status(500).json({ error: '处理支付回调失败' });
  }
}

/**
 * 查询支付状态
 */
async function getPaymentStatus(req, res) {
  try {
    const { orderId } = req.params;
    
    const order = await PaymentService.getPaymentOrder(orderId);
    if (!order) {
      return res.status(404).json({ error: '订单不存在' });
    }
    
    res.json({ status: order.status });
  } catch (error) {
    logger.error('查询支付状态失败', { error: error.message });
    res.status(500).json({ error: '查询支付状态失败' });
  }
}

module.exports = {
  createPaymentOrder,
  paymentCallback,
  getPaymentStatus
};